

import React, { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import Layout from '../../components/Layout';
import authApi from '../../api/auth';
import studentApi, { MyCourseFormDto } from '../../api/student';

interface CourseData {
  id: number;
  name: string;
  period: string;
  price: number;
  registrationTime: string;
  startTime: string;
  endTime: string;
  courseHours: number;
  testTime: string;
  leaderId: number;
  corpId: number;
  subCategoryId: number;
  description: string;
  createTime: string;
  updateTime: string;
}

 

interface ApiResponse {
  code: number;
  message: string;
  data: CourseData[] | {
    records: CourseData[];
    total: number;
    size: number;
    current: number;
    pages: number;
  };
}

const CourseListPage: React.FC = () => {
  const navigate = useNavigate();
  
  // 状态管理
  const [courseSearchTerm, setCourseSearchTerm] = useState('');
  
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [coursesData, setCoursesData] = useState<CourseData[]>([]);
  const [loading, setLoading] = useState(false);
  const [totalCourses, setTotalCourses] = useState(0);
  const [totalPages, setTotalPages] = useState(0);
  const [error, setError] = useState<string | null>(null);
  const [enrolledCourseIds, setEnrolledCourseIds] = useState<Set<number>>(new Set());

  // 获取课程数据
  const fetchCourses = async () => {
    try {
      setLoading(true);
      setError(null);
      
      // 获取token
      const token = localStorage.getItem('token');
      console.log('正在调用API:', `http://localhost:8086/course/list?pageNo=${currentPage}&pageSize=${pageSize}`);
      console.log('Token:', token ? `存在 (${token.substring(0, 20)}...)` : '不存在');
      
      if (!token) {
        throw new Error('未找到登录凭证，请先登录');
      }
      
      const headers: Record<string, string> = {
        'Content-Type': 'application/json',
      };
      
      // 如果有token，添加Authorization头
      if (token) {
        headers['Authorization'] = `Bearer ${token}`;
      }
      
      const response = await fetch(`http://localhost:8086/course/list?pageNo=${currentPage}&pageSize=${pageSize}`, {
        method: 'GET',
        headers,
        credentials: 'include', // 包含cookies和session
      });
      
      console.log('API响应状态:', response.status);
      
      if (!response.ok) {
        if (response.status === 401) {
          throw new Error('需要登录才能访问课程数据');
        } else if (response.status === 404) {
          throw new Error('课程服务暂时不可用');
        } else {
          throw new Error(`服务器错误 (${response.status})`);
        }
      }
      
      const result: ApiResponse = await response.json();
      console.log('API响应数据:', result);
      
      if (result.code === 0 && result.data) {
        // 检查data是数组还是对象
        if (Array.isArray(result.data)) {
          // data直接是数组
          setCoursesData(result.data);
          setTotalCourses(result.data.length);
          setTotalPages(Math.ceil(result.data.length / pageSize));
          console.log('课程数据加载成功:', result.data.length, '条记录');
        } else {
          // data是包含records的对象
          setCoursesData(result.data.records);
          setTotalCourses(result.data.total);
          setTotalPages(result.data.pages);
          console.log('课程数据加载成功:', result.data.records.length, '条记录');
        }
      } else {
        console.error('获取课程数据失败:', result.message);
        setError(result.message || '获取课程数据失败');
        setCoursesData([]);
        setTotalCourses(0);
        setTotalPages(0);
      }
    } catch (error) {
      console.error('API调用失败:', error);
      setError(error instanceof Error ? error.message : '网络连接失败，请检查网络或稍后重试');
      setCoursesData([]);
      setTotalCourses(0);
      setTotalPages(0);
    } finally {
      setLoading(false);
    }
  };

  // 页面加载时获取数据
  useEffect(() => {
    fetchCourses();
  }, [currentPage, pageSize]);

  // 获取当前登录用户已报名课程列表
  useEffect(() => {
    const fetchEnrolled = async () => {
      try {
        const token = localStorage.getItem('token');
        if (!token) return; // 未登录则无需显示已报名标记

        const userResp = await authApi.getUser();
        const userId = userResp?.data?.id;
        if (!userId) return;

        const resp = await studentApi.getEnrolledCourses(userId);
        const list: MyCourseFormDto[] = resp?.data || [];
        const idSet = new Set<number>(list.map(item => Number(item.courseId)));
        setEnrolledCourseIds(idSet);
      } catch (err) {
        console.warn('获取已报名课程失败：', err);
        // 静默失败，不影响课程列表展示
      }
    };

    fetchEnrolled();
  }, []);


  // 事件处理函数
  const handleCourseSearch = () => {
    console.log('搜索课程:', courseSearchTerm);
    // 这里可以添加实际的搜索逻辑
  };



  

  const handleCourseCardClick = (courseId: number) => {
    navigate(`/course-detail?courseId=${courseId}`);
  };

  const handlePageChange = (pageNum: number) => {
    setCurrentPage(pageNum);
    console.log('跳转到第', pageNum, '页');
  };

  const handlePageSizeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const newPageSize = parseInt(e.target.value);
    setPageSize(newPageSize);
    setCurrentPage(1); // 重置到第一页
    console.log('每页显示:', newPageSize, '条');
  };

  

  

  

  

  // 处理HTML描述，提取纯文本
  const getPlainTextDescription = (htmlDescription: string) => {
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = htmlDescription;
    const text = tempDiv.textContent || tempDiv.innerText || '';
    return text.length > 100 ? text.substring(0, 100) + '...' : text;
  };

  // 格式化日期
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
  };

  return (
    <Layout title="课程中心 - 学途">
      <div className="min-h-screen bg-gray-50">
        {/* 主内容区域 */}
        <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
            {/* 页面头部 */}
            <div className="mb-8">
              <nav className="text-sm text-gray-600 mb-4">
                <Link to="/home" className="hover:text-blue-600">首页</Link>
                <span className="mx-2">/</span>
                <span className="text-gray-900">课程中心</span>
              </nav>
              <h1 className="text-3xl font-bold text-gray-900">课程中心</h1>
              <p className="text-gray-600 mt-2">发现优质课程，提升专业技能</p>
            </div>

            {/* 工具栏区域 */}
            <div className="bg-white rounded-xl shadow-lg p-6 mb-8">
              {/* 搜索框 */}
              <div className="mb-6">
                <div className="relative max-w-md">
                  <input 
                    type="text" 
                    placeholder="搜索课程名称、讲师..." 
                    value={courseSearchTerm}
                    onChange={(e) => setCourseSearchTerm(e.target.value)}
                    className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  />
                  <i className="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                  <button 
                    onClick={handleCourseSearch}
                    className="absolute right-2 top-1/2 transform -translate-y-1/2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                  >
                    搜索
                  </button>
                </div>
              </div>

              
            </div>

            {/* 课程列表 */}
            <div className="mb-8">
              {loading ? (
                <div className="flex justify-center items-center py-12">
                  <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
                  <span className="ml-3 text-gray-600">加载中...</span>
                </div>
              ) : error ? (
                <div className="bg-white rounded-xl shadow-lg p-12 text-center">
                  <div className="text-red-500 mb-4">
                    <i className="fas fa-exclamation-triangle text-4xl"></i>
                  </div>
                  <h3 className="text-lg font-semibold text-gray-900 mb-2">加载失败</h3>
                  <p className="text-gray-600 mb-4">{error}</p>
                  <div className="flex justify-center space-x-3">
                    {error.includes('登录') ? (
                      <Link 
                        to="/login"
                        className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                      >
                        去登录
                      </Link>
                    ) : (
                      <button 
                        onClick={fetchCourses}
                        className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                      >
                        重试
                      </button>
                    )}
                  </div>
                </div>
              ) : coursesData.length === 0 ? (
                <div className="bg-white rounded-xl shadow-lg p-12 text-center">
                  <div className="text-gray-400 mb-4">
                    <i className="fas fa-book-open text-4xl"></i>
                  </div>
                  <h3 className="text-lg font-semibold text-gray-900 mb-2">暂无课程</h3>
                  <p className="text-gray-600">当前没有可用的课程，请稍后再试</p>
                </div>
              ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  {coursesData.map((course) => (
                    <div 
                      key={course.id}
                      className="relative bg-white rounded-xl shadow-lg hover:shadow-xl overflow-hidden cursor-pointer transition-all"
                      onClick={() => handleCourseCardClick(course.id)}
                    >
                      {/* 已报名盖章戳（大圆形，中心镂空） */}
                      {enrolledCourseIds.has(Number(course.id)) && (
                        <div className="absolute top-3 right-3 pointer-events-none select-none">
                          <div className="relative flex items-center justify-center w-20 h-20 md:w-24 md:h-24 rounded-full border-[3px] md:border-[4px] border-red-500 text-red-600 font-bold -rotate-12 bg-transparent shadow-sm">
                            <span className="text-xs md:text-sm tracking-widest">已报名</span>
                            {/* 内圈虚线，增强盖章质感，中心保持镂空 */}
                            <div className="absolute inset-2 md:inset-3 rounded-full border border-dashed border-red-400 opacity-70"></div>
                          </div>
                        </div>
                      )}
                      <div className="w-full h-48 bg-gradient-to-br from-blue-400 to-purple-500 flex items-center justify-center">
                        <div className="text-white text-center">
                          <i className="fas fa-graduation-cap text-4xl mb-2"></i>
                          <p className="text-sm">课程封面</p>
                        </div>
                      </div>
                      <div className="p-6">
                        <div className="flex items-center space-x-2 mb-2">
                          <span className="px-2 py-1 text-xs rounded-full bg-blue-100 text-blue-600">
                            {course.period}
                          </span>
                          <span className="px-2 py-1 bg-gray-100 text-gray-600 text-xs rounded-full">
                            {course.courseHours}课时
                          </span>
                        </div>
                        <h3 className="font-semibold text-gray-900 mb-2">{course.name}</h3>
                        <p className="text-gray-600 text-sm mb-4">{getPlainTextDescription(course.description)}</p>
                        <div className="flex items-center justify-between mb-4">
                          <div className="flex items-center space-x-2">
                            <div className="w-6 h-6 bg-gray-300 rounded-full flex items-center justify-center">
                              <i className="fas fa-user text-gray-600 text-xs"></i>
                            </div>
                            <span className="text-gray-600 text-sm">讲师ID: {course.leaderId}</span>
                          </div>
                          <span className="text-lg font-bold text-blue-600">¥{course.price}</span>
                        </div>
                        <div className="flex items-center justify-between">
                          <div className="flex items-center space-x-1 text-gray-600 text-sm">
                            <i className="fas fa-clock"></i>
                            <span>开课时间</span>
                          </div>
                          <div className="text-gray-600 text-sm">
                            <i className="fas fa-calendar-alt mr-1"></i>
                            <span>{formatDate(course.startTime)}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* 分页区域 */}
            <div className="bg-white rounded-xl shadow-lg p-6">
              <div className="flex flex-col md:flex-row md:items-center md:justify-between space-y-4 md:space-y-0">
                <div className="text-sm text-gray-600">
                  显示第 <span className="font-medium">{(currentPage - 1) * pageSize + 1}-{Math.min(currentPage * pageSize, totalCourses)}</span> 条，共 <span className="font-medium">{totalCourses}</span> 条记录
                </div>
                
                <div className="flex items-center space-x-2">
                  <button 
                    className="px-3 py-2 border border-gray-300 rounded-lg text-gray-600 hover:bg-blue-600 hover:text-white transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                    disabled={currentPage === 1}
                    onClick={() => handlePageChange(currentPage - 1)}
                  >
                    <i className="fas fa-chevron-left"></i>
                  </button>
                  
                  {/* 动态生成页码按钮 */}
                  {Array.from({ length: Math.min(totalPages, 5) }, (_, i) => {
                    const pageNum = i + 1;
                    return (
                      <button 
                        key={pageNum}
                        className={`px-3 py-2 border rounded-lg ${
                          currentPage === pageNum ? 'border-blue-600 bg-blue-600 text-white' : 'border-gray-300 text-gray-600 hover:bg-blue-600 hover:text-white'
                        } transition-colors`}
                        onClick={() => handlePageChange(pageNum)}
                      >
                        {pageNum}
                      </button>
                    );
                  })}
                  
                  {totalPages > 5 && (
                    <>
                      <span className="px-3 py-2 text-gray-600">...</span>
                      <button 
                        className={`px-3 py-2 border rounded-lg ${
                          currentPage === totalPages ? 'border-blue-600 bg-blue-600 text-white' : 'border-gray-300 text-gray-600 hover:bg-blue-600 hover:text-white'
                        } transition-colors`}
                        onClick={() => handlePageChange(totalPages)}
                      >
                        {totalPages}
                      </button>
                    </>
                  )}
                  
                  <button 
                    className="px-3 py-2 border border-gray-300 rounded-lg text-gray-600 hover:bg-blue-600 hover:text-white transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                    disabled={currentPage === totalPages}
                    onClick={() => handlePageChange(currentPage + 1)}
                  >
                    <i className="fas fa-chevron-right"></i>
                  </button>
                </div>
                
                <div className="flex items-center space-x-2">
                  <span className="text-sm text-gray-600">每页显示:</span>
                  <select 
                    value={pageSize}
                    onChange={handlePageSizeChange}
                    className="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="10">10</option>
                    <option value="20">20</option>
                    <option value="30">30</option>
                    <option value="50">50</option>
                  </select>
                </div>
              </div>
            </div>
          </div>
        </div>
    </Layout>
  );
};

export default CourseListPage;

